<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import TiptapEditor from '../components/TiptapEditor.vue'

// 路由
const router = useRouter()
const route = useRoute()

// 连接状态
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')

// 保存提示信息
const saveMessage = ref('')
const saveMessageType = ref<'success' | 'error'>('success')

// WebSocket连接
let socket: WebSocket | null = null

// 用户信息 - 扩展用户对象以包含更多信息
const users = ref<Array<{ 
  id: string; 
  name: string; 
  color: string; 
  cursor?: { x: number; y: number }; 
  selection?: string;
  status: 'viewing' | 'editing' | 'left';
  lastActive: Date;
}>>([])

// 当前用户ID
const currentUserId = ref('')

// 用户名
const userName = ref('')

// 用户名是否已设置
const userNameSet = ref(true) // 默认为true，因为我们从localStorage获取用户名

// 编辑器内容
const content = ref('')

// Tiptap编辑器引用
const tiptapEditor = ref<InstanceType<typeof TiptapEditor> | null>(null)

// 文档信息
const documentId = ref<number | null>(null)
const documentTitle = ref('未命名文档')
const documentOutline = ref<Array<{ id: string; level: number; text: string }>>([])

// 展开/收缩状态
const isSidebarCollapsed = ref(false)
const isOutlineCollapsed = ref(false)
const isCollaborationCollapsed = ref(false)

// 最后编辑时间
let lastEditTime: number | null = null
let editTimeout: number | null = null

// 发送用户活动更新
const sendUserActivity = (activity: 'viewing' | 'editing') => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    const userUpdateMessage = {
      type: 'user-update',
      user: {
        id: currentUserId.value,
        status: activity,
        lastActive: new Date(),
        documentId: documentId.value
      }
    };
    console.log('Sending user activity update:', userUpdateMessage);
    socket.send(JSON.stringify(userUpdateMessage));
  }
}

// 当用户开始编辑时调用
const onEditorInput = (newContent: string) => {
  content.value = newContent;
  
  // 发送内容更新到服务器
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({
      type: 'document-update',
      content: content.value,
      documentId: documentId.value
    }));
    
    // 更新用户状态为正在编辑
    sendUserActivity('editing');
    
    // 记录最后编辑时间
    lastEditTime = Date.now();
    
    // 清除之前的定时器
    if (editTimeout) {
      clearTimeout(editTimeout);
    }
    
    // 设置定时器，在用户停止编辑2秒后将其状态改回查看
    editTimeout = window.setTimeout(() => {
      if (lastEditTime && Date.now() - lastEditTime >= 2000) {
        sendUserActivity('viewing');
        lastEditTime = null;
      }
    }, 2000);
  }
  
  // 更新文档大纲
  updateDocumentOutline()
}

// 设置用户名
const setUserName = () => {
  if (userName.value.trim()) {
    userNameSet.value = true
    // 连接到WebSocket服务器
    connect()
  }
}

// 从localStorage获取用户信息
const getUserInfoFromStorage = () => {
  const user = localStorage.getItem('user')
  if (user) {
    try {
      const userData = JSON.parse(user)
      userName.value = userData.username || ''
      currentUserId.value = 'user_' + userData.id  // 使用用户ID生成唯一标识
    } catch (e) {
      console.error('Error parsing user data:', e)
    }
  }
}

// 生成随机颜色
const getRandomColor = () => {
  const colors = [
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF',
    '#FFA500', '#800080', '#008000', '#000080', '#800000', '#808000'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

// 连接到WebSocket服务器
const connect = () => {
  console.log('Attempting to connect to WebSocket server with:', { userName: userName.value, currentUserId: currentUserId.value, documentId: documentId.value })
  connectionStatus.value = 'connecting'
  
  // 连接到WebSocket服务器
  socket = new WebSocket('ws://localhost:3000')  // 使用3000端口
  
  socket.onopen = () => {
    console.log('Connected to WebSocket server')
    connectionStatus.value = 'connected'
    
    // 发送用户加入消息
    if (socket) {
      const userJoinMessage = {
        type: 'user-join',
        user: { 
          id: currentUserId.value, 
          name: userName.value, 
          color: getRandomColor(),
          documentId: documentId.value,  // 添加文档ID
          status: 'viewing',
          lastActive: new Date()
        }
      }
      console.log('Sending user-join message:', userJoinMessage)
      socket.send(JSON.stringify(userJoinMessage))
      
      // 将当前用户添加到用户列表中
      users.value.push({
        id: currentUserId.value,
        name: userName.value,
        color: getRandomColor(),
        documentId: documentId.value,
        status: 'viewing',
        lastActive: new Date()
      });
    }
  }
  
  socket.onmessage = (event) => {
    let data;
    try {
      data = JSON.parse(event.data);
    } catch (e) {
      console.error('Error parsing message:', event.data);
      return;
    }
    
    console.log('EditorView - Received message:', data);
    console.log('EditorView - Current documentId:', documentId.value);
    
    // 只处理当前文档的消息
    if (data.documentId !== undefined && data.documentId !== documentId.value) {
      console.log('EditorView - Ignoring message for different document:', data.documentId, 'vs', documentId.value);
      return;
    }
    
    switch (data.type) {
      case 'document-update':
        console.log('EditorView - Processing document-update, content length:', data.content?.length);
        // 更新编辑器内容
        content.value = data.content;
        // 更新文档大纲
        updateDocumentOutline();
        console.log('EditorView - Updated document content');
        break;
        
      case 'user-join':
        // 添加新用户
        if (!users.value.find(u => u.id === data.user.id)) {
          users.value.push({
            ...data.user,
            status: data.user.status || 'viewing',
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          });
        }
        break;
        
      case 'user-update':
        // 更新用户信息
        const userIndex = users.value.findIndex(u => u.id === data.user.id);
        if (userIndex !== -1) {
          users.value[userIndex] = { 
            ...users.value[userIndex], 
            ...data.user,
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          };
        } else {
          users.value.push({
            ...data.user,
            status: data.user.status || 'viewing',
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          });
        }
        console.log('Updated users list:', users.value);
        break;
        
      case 'user-leave':
        // 更新用户状态为已离开
        const leavingUserIndex = users.value.findIndex(u => u.id === data.user.id);
        if (leavingUserIndex !== -1) {
          users.value[leavingUserIndex].status = 'left';
          users.value[leavingUserIndex].lastActive = new Date();
        }
        break;
        
      default:
        console.log('Unknown message type:', data.type);
    }
  };
  
  socket.onclose = (event) => {
    console.log('Disconnected from WebSocket server', event)
    connectionStatus.value = 'disconnected'
    
    // 清除定时器
    if (editTimeout) {
      clearTimeout(editTimeout);
      editTimeout = null;
    }
  }
  
  socket.onerror = (error) => {
    console.error('WebSocket error:', error)
    connectionStatus.value = 'disconnected'
    
    // 清除定时器
    if (editTimeout) {
      clearTimeout(editTimeout);
      editTimeout = null;
    }
  }
}

// 保存文档
const saveDocument = async () => {
  if (!documentId.value) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${documentId.value}`, {  // 改为3000端口
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: documentTitle.value,
        content: content.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      console.log('Document saved successfully')
      // 显示成功提示
      saveMessage.value = '文档保存成功！'
      saveMessageType.value = 'success'
      // 3秒后清除提示
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    } else {
      console.error('Failed to save document:', data.error)
      // 显示错误提示
      saveMessage.value = '保存失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      // 3秒后清除提示
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Save document error:', err)
    // 显示错误提示
    saveMessage.value = '保存失败：网络错误'
    saveMessageType.value = 'error'
    // 3秒后清除提示
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 预览文档
const previewDocument = () => {
  // 先保存当前文档
  saveDocument()
  
  // 跳转到预览页面
  if (documentId.value) {
    router.push(`/preview?id=${documentId.value}`)
  }
}

// 加载文档
const loadDocument = async () => {
  const id = route.query.id as string
  console.log('Loading document with ID:', id)
  if (!id) {
    console.log('No document ID provided')
    return
  }
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${id}`)  // 改为3000端口
    const data = await response.json()
    console.log('Document API response:', data)
    
    if (response.ok) {
      if (data && data.document) {
        documentId.value = data.document.id
        documentTitle.value = data.document.title
        content.value = data.document.content
        
        // 更新文档大纲
        updateDocumentOutline()
        console.log('Document loaded successfully:', { 
          id: documentId.value, 
          title: documentTitle.value, 
          content: content.value 
        })
      } else {
        console.error('Document data is missing in response:', data)
      }
    } else {
      console.error('Failed to load document:', data.error)
    }
  } catch (err) {
    console.error('Load document error:', err)
  }
}

// 更新文档大纲
const updateDocumentOutline = () => {
  // 简化处理，实际项目中可以从content中解析标题
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = content.value
  
  const headings = tempDiv.querySelectorAll('h1, h2, h3, h4, h5, h6')
  const outline = Array.from(headings).map((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    return {
      id: `heading-${index}`,
      level,
      text: heading.textContent || ''
    }
  })
  
  documentOutline.value = outline
}

// 滚动到指定标题
const scrollToHeading = (id: string) => {
  // 在实际应用中，这里会滚动到指定的标题位置
  console.log('Scroll to heading:', id)
}

// 返回首页
const goHome = () => {
  router.push('/')
}

// 切换侧边栏展开/收缩
const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}

// 切换大纲展开/收缩
const toggleOutline = () => {
  isOutlineCollapsed.value = !isOutlineCollapsed.value
}

// 切换协作信息展开/收缩
const toggleCollaboration = () => {
  isCollaborationCollapsed.value = !isCollaborationCollapsed.value
}

onMounted(async () => {
  console.log('EditorView mounted')
  
  // 从localStorage获取用户信息
  getUserInfoFromStorage()
  console.log('User info after getUserInfoFromStorage:', { userName: userName.value, currentUserId: currentUserId.value })
  
  // 加载文档
  await loadDocument()
  console.log('Document info after loadDocument:', { documentId: documentId.value, documentTitle: documentTitle.value })
  
  // 检查是否应该连接WebSocket（在加载文档后）
  console.log('Checking connection conditions after document load:', { userName: userName.value, documentId: documentId.value, hasUserName: !!userName.value, hasDocumentId: !!documentId.value })
  if (userName.value && documentId.value) {
    console.log('Connecting to WebSocket server')
    connect()
  } else {
    console.log('Skipping WebSocket connection due to missing info')
  }
})

onUnmounted(() => {
  console.log('EditorView unmounted')
  // 断开WebSocket连接
  if (socket) {
    // 发送用户离开消息
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({
        type: 'user-leave',
        user: { id: currentUserId.value }
      }))
    }
    socket.close()
  }
  
  // 清除定时器
  if (editTimeout) {
    clearTimeout(editTimeout);
    editTimeout = null;
  }
  
  // 保存文档
  saveDocument()
})
</script>

<template>
  <div class="editor">
    <div class="editor-header">
      <div class="left-actions">
        <input 
          v-model="documentTitle" 
          class="document-title" 
          placeholder="文档标题"
          @blur="saveDocument"
        />
      </div>
      
      <div class="center-actions">
        <!-- 协作用户头像显示 -->
        <div class="collaborators-container">
          <div class="collaborators-list">
            <!-- 正在编辑的用户 -->
            <div 
              v-for="user in users.filter(u => u.status === 'editing')" 
              :key="'editing-' + user.id" 
              class="collaborator-avatar editing"
              :style="{ borderColor: user.color }"
              :title="user.name + ' (正在编辑)'"
            >
              <div class="avatar-content" :style="{ backgroundColor: user.color }">
                {{ user.name.charAt(0) }}
              </div>
            </div>
            
            <!-- 正在查看的用户 -->
            <div 
              v-for="user in users.filter(u => u.status === 'viewing')" 
              :key="'viewing-' + user.id" 
              class="collaborator-avatar viewing"
              :style="{ borderColor: user.color }"
              :title="user.name + ' (正在查看)'"
            >
              <div class="avatar-content" :style="{ backgroundColor: user.color }">
                {{ user.name.charAt(0) }}
              </div>
            </div>
            
            <!-- 最近查看过的用户 -->
            <div 
              v-for="user in users.filter(u => u.status === 'left')" 
              :key="'left-' + user.id" 
              class="collaborator-avatar left"
              :style="{ borderColor: user.color }"
              :title="user.name + ' (最近查看过)'"
            >
              <div class="avatar-content" :style="{ backgroundColor: user.color }">
                {{ user.name.charAt(0) }}
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="right-actions">
        <!-- 连接状态小图标 -->
        <div class="connection-status-icon" :class="connectionStatus">
          <span v-if="connectionStatus === 'connected'">●</span>
          <span v-else-if="connectionStatus === 'connecting'">◐</span>
          <span v-else>○</span>
        </div>
        
        <!-- 保存按钮 -->
        <button @click="saveDocument" class="icon-button" title="保存">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 21H5C3.89543 21 3 20.1046 3 19V5C3 3.89543 3.89543 3 5 3H16.1716C16.702 3 17.2107 3.21071 17.5858 3.58579L20.4142 6.41421C20.7893 6.78929 21 7.29799 21 7.82843V19C21 20.1046 20.1046 21 19 21Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M17 21V13H7V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M7 3V8H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
        
        <!-- 预览按钮 -->
        <button @click="previewDocument" class="icon-button" title="预览">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M1 12C1 12 5 4 12 4C19 4 23 12 23 12C23 12 19 20 12 20C5 20 1 12 1 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
        
        <!-- 返回首页按钮 -->
        <button @click="goHome" class="icon-button" title="返回首页">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 12H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M3 12L10 19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M3 12L10 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
    
    <!-- 保存提示 -->
    <div v-if="saveMessage" class="save-message" :class="saveMessageType">
      {{ saveMessage }}
    </div>
    
    <div class="editor-container" v-if="userNameSet">
      <div class="main-content">
        <!-- Tiptap编辑器 -->
        <TiptapEditor 
          v-model="content" 
          @update:modelValue="onEditorInput"
          ref="tiptapEditor"
        />
        
        <!-- 光标位置指示器 -->
        <div 
          v-for="user in users.filter(u => u.id !== currentUserId && u.cursor && u.cursor.x !== undefined && u.cursor.y !== undefined)" 
          :key="user.id"
          class="cursor-indicator"
          :style="{
            left: (user.cursor?.x || 0) + 'px',
            top: (user.cursor?.y || 0) + 'px',
            backgroundColor: user.color
          }"
          :title="user.name"
        >
          <div class="cursor-name" :style="{ backgroundColor: user.color }">
            {{ user.name }}
          </div>
        </div>
      </div>
      
      <!-- 右侧边栏 -->
      <div class="sidebar" :class="{ collapsed: isSidebarCollapsed }">
        <div class="sidebar-toggle" @click="toggleSidebar">
          {{ isSidebarCollapsed ? '▶' : '◀' }}
        </div>
        
        <div v-show="!isSidebarCollapsed" class="sidebar-content">
          <!-- 文档大纲 -->
          <div class="sidebar-section">
            <div class="section-header" @click="toggleOutline">
              <h3>文档大纲</h3>
              <span class="collapse-toggle">{{ isOutlineCollapsed ? '+' : '-' }}</span>
            </div>
            <div v-show="!isOutlineCollapsed" class="section-content">
              <div class="document-outline" v-if="documentOutline.length > 0">
                <ul>
                  <li 
                    v-for="(item, index) in documentOutline" 
                    :key="index" 
                    :class="`outline-item outline-${item.level}`"
                    @click="scrollToHeading(item.id)"
                  >
                    {{ item.text }}
                  </li>
                </ul>
              </div>
              <div v-else class="no-outline">
                暂无大纲
              </div>
            </div>
          </div>
          
          <!-- 协作用户信息 -->
          <div class="sidebar-section">
            <div class="section-header" @click="toggleCollaboration">
              <h3>协作用户</h3>
              <span class="collapse-toggle">{{ isCollaborationCollapsed ? '+' : '-' }}</span>
            </div>
            <div v-show="!isCollaborationCollapsed" class="section-content">
              <div class="collaboration-info">
                <!-- 正在编辑的用户 -->
                <div class="user-category">
                  <h4>正在编辑:</h4>
                  <div v-for="user in users.filter(u => u.status === 'editing')" :key="user.id" class="user" :style="{ color: user.color }">
                    {{ user.name }}
                    <span v-if="user.id === currentUserId">(您)</span>
                  </div>
                  <div v-if="users.filter(u => u.status === 'editing').length === 0" class="no-users">暂无用户正在编辑</div>
                </div>
                
                <!-- 正在查看的用户 -->
                <div class="user-category">
                  <h4>正在查看:</h4>
                  <div v-for="user in users.filter(u => u.status === 'viewing')" :key="user.id" class="user" :style="{ color: user.color }">
                    {{ user.name }}
                    <span v-if="user.id === currentUserId">(您)</span>
                  </div>
                  <div v-if="users.filter(u => u.status === 'viewing').length === 0" class="no-users">暂无用户正在查看</div>
                </div>
                
                <!-- 已离开的用户 -->
                <div class="user-category">
                  <h4>最近查看过:</h4>
                  <div v-for="user in users.filter(u => u.status === 'left')" :key="user.id" class="user left-user" :style="{ color: user.color }">
                    {{ user.name }}
                  </div>
                  <div v-if="users.filter(u => u.status === 'left').length === 0" class="no-users">暂无用户记录</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.editor {
  font-family: Arial, sans-serif;
  padding: 10px;
  max-width: 100%;
  margin: 0 auto;
  height: calc(100vh - 20px);
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f8f9fa;
  border-radius: 5px;
}

.left-actions {
  flex: 1;
}

.document-title {
  font-size: 1.2em;
  border: none;
  outline: none;
  background: transparent;
  font-weight: bold;
  width: 100%;
}

.center-actions {
  flex: 2;
  display: flex;
  justify-content: center;
}

.collaborators-container {
  display: flex;
  align-items: center;
  height: 30px;
}

.collaborators-list {
  display: flex;
  align-items: center;
}

.collaborator-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 2px solid;
  margin-left: -8px;
  position: relative;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}

.collaborator-avatar:first-child {
  margin-left: 0;
}

.collaborator-avatar:hover {
  transform: scale(1.1);
  z-index: 10;
}

.avatar-content {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 12px;
}

.collaborator-avatar.editing {
  border-width: 2px;
}

.collaborator-avatar.viewing {
  border-width: 1px;
  opacity: 0.8;
}

.collaborator-avatar.left {
  border-width: 1px;
  opacity: 0.5;
}

.right-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.connection-status-icon {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}

.connection-status-icon.connected {
  color: #4caf50;
}

.connection-status-icon.connecting {
  color: #ff9800;
}

.connection-status-icon.disconnected {
  color: #f44336;
}

.icon-button {
  padding: 5px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-button:hover {
  background-color: #e9ecef;
}

/* 保存提示样式 */
.save-message {
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 10px;
  text-align: center;
  font-weight: bold;
  font-size: 0.9em;
}

.save-message.success {
  background-color: #4caf50;
  color: white;
}

.save-message.error {
  background-color: #f44336;
  color: white;
}

.editor-container {
  display: flex;
  gap: 15px;
  flex: 1;
  overflow: hidden;
}

.main-content {
  flex: 1;
  position: relative;
  border: 1px solid #ddd;
  border-radius: 5px;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f9f9f9;
  position: relative;
  transition: all 0.3s ease;
  overflow: hidden;
}

.sidebar.collapsed {
  width: 30px;
}

.sidebar-toggle {
  position: absolute;
  top: 50%;
  left: -15px;
  transform: translateY(-50%);
  width: 30px;
  height: 60px;
  background-color: #ddd;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  font-size: 12px;
}

.sidebar-content {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
}

.sidebar-section {
  margin-bottom: 15px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 8px 0;
  border-bottom: 1px solid #ddd;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 1em;
}

.collapse-toggle {
  font-weight: bold;
  font-size: 14px;
}

.section-content {
  padding: 8px 0;
}

.cursor-indicator {
  position: absolute;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  pointer-events: none;
}

.cursor-name {
  position: absolute;
  top: -20px;
  left: -10px;
  padding: 3px 6px;
  border-radius: 3px;
  color: white;
  font-size: 10px;
  white-space: nowrap;
}

.collaboration-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.user-category {
  margin-bottom: 10px;
}

.user-category h4 {
  margin: 8px 0 4px 0;
  color: #555;
  font-size: 0.9em;
}

.collaboration-info .user {
  margin-bottom: 2px;
  padding: 2px 0;
  font-size: 0.9em;
}

.collaboration-info .left-user {
  opacity: 0.6;
}

.collaboration-info .no-users {
  color: #888;
  font-style: italic;
  font-size: 0.8em;
}

.document-outline h3 {
  margin-bottom: 8px;
}

.document-outline ul {
  list-style-type: none;
  padding: 0;
}

.document-outline .outline-item {
  margin-bottom: 4px;
  cursor: pointer;
  padding: 4px;
  border-radius: 2px;
  font-size: 0.9em;
}

.document-outline .outline-item:hover {
  background-color: #e0e0e0;
}

.document-outline .outline-1 {
  font-weight: bold;
  font-size: 1em;
}

.document-outline .outline-2 {
  margin-left: 15px;
  font-size: 0.95em;
}

.document-outline .outline-3 {
  margin-left: 30px;
  font-size: 0.9em;
}

.document-outline .outline-4 {
  margin-left: 45px;
  font-size: 0.85em;
}

.document-outline .outline-5 {
  margin-left: 60px;
  font-size: 0.8em;
}

.document-outline .outline-6 {
  margin-left: 75px;
  font-size: 0.75em;
}

.no-outline {
  color: #888;
  font-style: italic;
  text-align: center;
  padding: 15px 0;
  font-size: 0.9em;
}

</style>